package com.act.moudles.user.service.impl;

import com.act.components.UserComponent;
import com.act.constant.LoginTypeEnums;
import com.act.moudles.user.dao.OrgDao;
import com.act.moudles.user.entity.Org;
import com.act.moudles.user.service.OrgService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;


/**
 * 部门Service
 * @author monxz
 * @version 2023-02-06
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrgServiceImpl extends ServiceImpl<OrgDao, Org> implements OrgService {

    @Resource
    private UserComponent userComponent;


    @Override
    public String  addOrg(Org org){
        //1. 去重验证
        String checkRes = checkUnion(org);
        if(StringUtils.isNotEmpty(checkRes)){
            return checkRes;
        }

        org.setDelFlag(1);
        org.setCreateBy(userComponent.getCurrentRealName(LoginTypeEnums.WEB.getType()));
        org.setCreateTime(new Date());
        save(org);
        return null;
    }

    @Override
    public String  updateOrg(Org org){
        //1. 去重验证
        String checkRes = checkUnion(org);
        if(StringUtils.isNotEmpty(checkRes)){
            return checkRes;
        }
        //2.查询父级
        org.setUpdateBy(userComponent.getCurrentRealName(LoginTypeEnums.WEB.getType()));
        org.setUpdateTime(new Date());
        updateById(org);
        return null;
    }


    /**
     * 重复检验
     * @param org
     * @return
     */
    private String checkUnion(Org org){
        LambdaQueryWrapper<Org> query = new LambdaQueryWrapper<>();
        query.ne(org.getOrgId() != null,Org::getOrgId,org.getOrgId());
        query.eq(StringUtils.isNotEmpty(org.getOrgName()),Org::getOrgName,org.getOrgName());
        query.eq(Org::getDelFlag,1);
        long counts = count(query);
        if(counts - 1L >= 0L){
            return  "公司名称重复";
        }
        query.clear();
        query.ne(org.getOrgId() != null,Org::getOrgId,org.getOrgId());
        query.eq(StringUtils.isNotEmpty(org.getOrgCode()),Org::getOrgCode,org.getOrgCode());
        query.eq(Org::getDelFlag,1);
        counts = count(query);
        if(counts - 1L >= 0L){
            return  "公司编码重复";
        }
        return null;
    }
}
